package com.acmedcare.framework.exchange.center.core.storage;

import com.acmedcare.framework.exchange.center.entity.bean.Consumer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ConsumerRepository {

  final JdbcTemplate jdbcTemplate;

  public ConsumerRepository(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }


  public List<Consumer> getConsumers() {

    try {

      List<Consumer> consumers = jdbcTemplate
          .query("select * from center_consumer", new ConsumerRowMapper());
      return consumers;
    } catch (EmptyResultDataAccessException e) {

      return null;
    }
  }

  public void insert(Consumer consumer) {

    String sql = "INSERT INTO center_consumer(consumer_id,name,task_name,plugin_name,consumer_name,status,create_time,version,group_name) VALUES(?,?,?,?,?,?,?,?,?)";
    try {

      jdbcTemplate.update(sql,
          new Object[]{consumer.getConsumerId(), consumer.getName(), consumer.getTaskName(),
              consumer.getPluginName(), consumer.getConsumerName(), consumer.getStatus().toString()
              , consumer.getCreateTime(), consumer.getVersion(), consumer.getGroupName()});
    } catch (Exception ex) {

      log.error("插入消费者数据异常!", ex);
    }
  }

  public void delete(Long id) {

    String sql = "DELETE FROM center_consumer WHERE consumer_id=?";
    try {

      jdbcTemplate.update(sql, new Object[]{id});
    } catch (Exception e) {
      log.error("删除消费器数据异常!", e);
    }
  }


  class ConsumerRowMapper implements RowMapper<Consumer> {

    @Override
    public Consumer mapRow(ResultSet resultSet, int i) throws SQLException {

      Consumer consumer = new Consumer();
      consumer.setConsumerId(resultSet.getLong("consumer_id"));
      consumer.setPluginName(resultSet.getString("plugin_name"));
      consumer.setName(resultSet.getString("name"));
      consumer.setVersion(resultSet.getString("version"));
      consumer.setTaskName(resultSet.getString("task_name"));
      consumer.setGroupName(resultSet.getString("group_name"));
      consumer.setConsumerName(resultSet.getString("consumer_name"));
      return consumer;
    }
  }
}
